<script setup lang="ts">
import { ref, watch } from 'vue';
import { $t } from '@/locales';
import { useForm, useFormRules } from '@/hooks/common/form';
import { fetchUserResetPasswordBatch } from '@/service/api';
import { useLoading } from '~/packages/hooks';

defineOptions({ name: 'UserResetPwdDialog' });

interface Emits {
  (e: 'submitted'): void;
}

const emit = defineEmits<Emits>();

interface Props {
  userIds: CommonType.IdType[];
}

const props = defineProps<Props>();

const visible = defineModel<boolean>('visible', {
  default: false
});

type FormModel = Api.System.User.UserResetPasswordModel;

function createDefaultModel(): FormModel {
  return {
    password: '',
    userIds: props.userIds || []
  };
}

const { formRef, validate, restoreValidation } = useForm();
const { createRequiredRule, patternRules } = useFormRules();

const model = ref<FormModel>(createDefaultModel());

// 初始化
function handleInitModel() {
  model.value = createDefaultModel();
}

type RuleKey = Extract<FormModel, 'password'>;
const rules = ref<Record<RuleKey, App.Global.FormRule>>({
  password: [createRequiredRule('请输入新的密码'), patternRules.pwd]
});

const { loading, startLoading, endLoading } = useLoading(false);

async function handleSubmit() {
  try {
    await validate();
    startLoading();
    // request
    const { error } = await fetchUserResetPasswordBatch(model.value);
    // success
    if (error) return;
    window.$message?.success($t('common.operateSuccess'));
    closeDialog();
    emit('submitted');
  } finally {
    endLoading();
  }
}

// 关闭对话框
function closeDialog() {
  visible.value = false;
}

watch(visible, () => {
  if (visible.value) {
    handleInitModel();
    restoreValidation();
  }
});
</script>

<template>
  <ElDialog v-model="visible" title="重置密码" width="600" :close-on-click-modal="false">
    <ElForm ref="formRef" v-loading="loading" :model="model" :rules="rules" :label-width="80" label-position="top">
      <ElFormItem label="新密码" prop="password">
        <ElInput v-model="model.password" maxlength="50" placeholder="请输入新密码" />
      </ElFormItem>
    </ElForm>
    <template #footer>
      <ElSpace v-loading="loading" :size="16">
        <ElButton @click="closeDialog">{{ $t('common.cancel') }}</ElButton>
        <ElButton type="primary" @click="handleSubmit">{{ $t('common.confirm') }}</ElButton>
      </ElSpace>
    </template>
  </ElDialog>
</template>

<style scoped>
:deep(.el-input-number .el-input__inner) {
  text-align: left;
}
</style>
